package org.chen.utils;

import lombok.experimental.UtilityClass;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Safelist;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@UtilityClass
public class HtmlParserUtil {
    
    private static final Map<String, Safelist> SAFELIST_CACHE = new ConcurrentHashMap<>();
    
    /**
     * 清理HTML内容，去除危险标签
     */
    public String cleanHtml(String html) {
        if (html == null) {
            return "";
        }
        return Jsoup.clean(html, Safelist.basic());
    }
    
    /**
     * 提取HTML中的纯文本内容
     */
    public String extractText(String html) {
        if (html == null) {
            return "";
        }
        Document doc = Jsoup.parse(html);
        return doc.text();
    }
    
    /**
     * 获取自定义的Safelist
     */
    public Safelist getSafelist(String type) {
        return SAFELIST_CACHE.computeIfAbsent(type, k -> {
            switch (k) {
                case "minimal":
                    return Safelist.none().addTags("b", "i", "br");
                    
                case "basic":
                    return Safelist.basic();
                    
                case "article":
                    return Safelist.basic()
                            .addTags("div", "span", "p", "h1", "h2", "h3", "h4", "h5", "h6")
                            .addAttributes(":all", "class", "id")
                            .addAttributes("a", "target")
                            .addProtocols("a", "target", "_blank");
                    
                case "full":
                    return Safelist.relaxed();
                    
                default:
                    return Safelist.basic();
            }
        });
    }
    
    /**
     * 使用自定义Safelist清理HTML
     */
    public String cleanHtml(String html, String safelistType) {
        if (html == null) {
            return "";
        }
        return Jsoup.clean(html, getSafelist(safelistType));
    }
}